package cn.kinoko.component;

import cn.kinoko.config.ConfigProperties;
import lombok.AllArgsConstructor;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.io.File;
import java.io.IOException;

/**
 * redisson配置类
 *
 * @author kinoko
 */
@AllArgsConstructor
@EnableConfigurationProperties(value = ConfigProperties.class)
@Import(ComponentImportSelector.class)
@Configuration
public class RedissonAutoConfiguration {

    private ConfigProperties configProperties;

    @Bean
    @ConditionalOnMissingBean(name = {"redissonClient"})
    public RedissonClient redissonClient() throws IOException {
        String file = configProperties.getFile();
        if (file == null) {
            throw new RuntimeException("can not found spring.redisson.file config from yaml");
        }
        if (file.startsWith("classpath:")) {
            return Redisson.create(Config.fromYAML(getClass().getClassLoader().getResourceAsStream(file.substring("classpath:".length()))));
        }
        return Redisson.create(Config.fromYAML(new File(file)));
    }

}
